package com.qf.utils;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.qf.pojo.vo.QfOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Component
public class AlipayUtils {

    @Value("${alipay.appid}")
    private String appid;
    @Value("${alipay.publickey}")
    private String publickey;
    @Value("${alipay.securtkey}")
    private String securtkey;
    @Value("${alipay.alipaypublickey}")
    private String alipaypublickey;
    @Value("${alipay.notifyUrl}")
    private String notifyUrl;
    @Value("${alipay.returnUrl}")
    private String returnUrl;
    @Value("${alipay.serverUrl}")
    private String serverUrl;

    private static Logger logger = LoggerFactory.getLogger(AlipayUtils.class);

    public String pay(QfOrder qfOrder){
        AlipayClient alipayClient =  new DefaultAlipayClient( serverUrl , appid, securtkey, "json", "utf-8", alipaypublickey, "RSA2");  //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest =  new AlipayTradePagePayRequest(); //创建API对应的request
        alipayRequest.setReturnUrl( returnUrl );
        alipayRequest.setNotifyUrl( notifyUrl ); //在公共参数中设置回跳和通知地址
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        JSONObject jsonObject = new JSONObject();
        model.setOutTradeNo(qfOrder.getOrderid());
        model.setTotalAmount(qfOrder.getOrderPay().toString());

        model.setSubject("课程购买");
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
//        jsonObject.put("out_trade_no",qfOrder.getOrderid());
//        jsonObject.put("product_code","FAST_INSTANT_TRADE_PAY");
//        jsonObject.put("total_amount",qfOrder.getOrderPay());
//        jsonObject.put("subject","课程购买！");
//        jsonObject.put("body","课程购买！");
        Date date = new Date(new Date().getTime()+300000);
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
        System.out.println(format);
       // jsonObject.put("time_expire",format);
        model.setBody("课程购买");
        model.setTimeExpire(format);
        alipayRequest.setBizModel(model); //填充业务参数
        String form= "" ;
        try  {
            form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
        }  catch  (AlipayApiException e) {
            e.printStackTrace();
        }
        return form;
    }


    public Map callBack(HttpServletRequest request){
        Map map = verfiryCallbackReq(request);
        //验签操作
        logger.debug("进入了支付宝的验签：参数为{}"+map);
        try {
            boolean  signVerified = AlipaySignature.rsaCheckV1(map, alipaypublickey, "utf-8", "RSA2");

            logger.debug("进入了支付宝的验签结果为："+signVerified);
           if (signVerified){
               return map;
           }else{
               return null;
           }

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
            return null;
    }


    public Map verfiryCallbackReq(HttpServletRequest request){
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }

        return retMap;
    }
}
